package com.rovinj_server.ui;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;


import com.rovinj_server.R;
import com.rovinj_server.adapter.PeopleRecyclerAdapter;
import com.rovinj_server.adapter.SameAdapter;
import com.rovinj_server.db.DBManager;
import com.rovinj_server.entity.InventorySub;
import com.rovinj_server.entity.InventoryTaskSub;
import com.rovinj_server.entity.People;
import com.rovinj_server.utisl.Directory;
import com.rovinj_server.utisl.ExcelUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jxl.write.WriteException;

/**
 * Created by Administrator on 2017/5/22.
 */

public class SameActivity extends AppCompatActivity {

    @Bind(R.id.fh)
    RelativeLayout mFh;
    @Bind(R.id.list_view)
    ListView mListView;
    private DBManager mDbManager;
    private SameAdapter mAdapter;
    private ProgressDialog mProgressDialog;
    private List<InventoryTaskSub> mTaskSubListXiang=new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activty_same);
        ButterKnife.bind(this);
        hidStater();
    }


    @Override
    protected void onStart() {
        super.onStart();
        query();
        initView();
    }

    /**
     * 隐藏状态栏
     */
    private void hidStater() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.hide();
    }
    private int checkNum;


    private void initView() {//getItemAtPosition

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                InventoryTaskSub mInventoryTaskSub = (InventoryTaskSub) mListView.getItemAtPosition(position);
                SameAdapter.ViewHolder holder = (SameAdapter.ViewHolder) view.getTag();
                    holder.cb.toggle();
                    mAdapter.getIsSelected().put(position, holder.cb.isChecked());

                // 调整选定条目
                if (holder.cb.isChecked() == true) {
                    checkNum++;
                } else {
                    checkNum--;
                }
                if (checkNum == 0) {

                }
                if (checkNum > 0) {

                    // xiayibu.setBackgroundResource(R.color.default_button_Normal);
                } else {

                    // xiayibu.setBackgroundResource(R.color.default_button_disabled);
                }

            }
        });
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                if (absListView.getLastVisiblePosition() == absListView.getCount() - 1 &&
                        i == SCROLL_STATE_IDLE) {
                    if (mTaskSubListXiang.size() > mAdapter.showCount) {
                        mAdapter.showCount += 20;
                        mAdapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
            }
        });
    }


    @OnClick({R.id.fh, R.id.but_shang, R.id.butt_cha, R.id.but_tiao_jiao})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fh:
                finish();
                break;
            case R.id.but_shang:
                delete();
                break;
            case R.id.butt_cha:
                query();
                break;
            case R.id.but_tiao_jiao:
                mProgressDialog = ProgressDialog.show(this, "", "正在查询数据请稍等");
                mProgressDialog.setCancelable(false);
                mProgressDialog.setIndeterminate(true);
                mProgressDialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        daoChu();
                    }
                }).start();
                break;
        }
    }
    private List<InventoryTaskSub> mSubListXiang;
    private void daoChu() {
        mSubListXiang = mDbManager.findTaskSubListXiang();
        mProgressDialog.dismiss();
        if (mSubListXiang != null && mSubListXiang.size()>0 ) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                 dialog();
                }
            });
        } else {
           runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    export();
                }
            });

        }

    }

    /**
     * 弹出对话框提示是否确定要重扫
     */
    private void dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("有重复数据确认导出数据吗");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                     export();
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }
     /**根据ID删除数据**/
    private void delete() {
        final ProgressDialog   mProgressDialog = ProgressDialog.show(this, "", "正在删除查询数据请稍等");
        mProgressDialog.setCancelable(false);
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.show();
         new Thread(new Runnable() {
             @Override
             public void run() {
                 HashMap<Integer, Boolean> isSelected = mAdapter.getIsSelected();
                 List<InventoryTaskSub> mDataScanng = new ArrayList<>();
                 Iterator iter = isSelected.entrySet().iterator();
                 while (iter.hasNext()) {
                     Map.Entry entry = (Map.Entry) iter.next();
                     int key = (int) entry.getKey();
                     boolean val = (boolean) entry.getValue();
                     if (val) {
                         mDataScanng.add(mTaskSubListXiang.get(key));
                     }
                 }
                 for (int i = 0; i < mDataScanng.size(); i++) {
                     String id = mDataScanng.get(i).getId();
                     mDbManager.deleteIdNull(id);

                 }
                 mProgressDialog.dismiss();
                 runOnUiThread(new Runnable() {
                     @Override
                     public void run() {
                        query();
                     }
                 });
             }
         }).start();

    }

    private void query() {

        mTaskSubListXiang.clear();
        final ProgressDialog   mProgressDialog = ProgressDialog.show(this, "", "正在查询数据请稍等");
        mProgressDialog.setCancelable(false);
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.show();
        mDbManager = new DBManager(this);
        mDbManager.copyDBFile();
        new Thread(new Runnable() {
            @Override
            public void run() {
                mTaskSubListXiang = mDbManager.findTaskSubListXiang();
                mProgressDialog.dismiss();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter = new SameAdapter(SameActivity.this, mTaskSubListXiang);
                        mListView.setAdapter(mAdapter);
                        mAdapter.notifyDataSetChanged();
                    }
                });

            }
        }).start();


     ;
    }
    private PeopleRecyclerAdapter peopleRecyclerAdapter;
    private void export() {

        final ProgressDialog progressDialog = ProgressDialog.show(SameActivity.this, "", "正在导出数据请稍等");
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(true);
        progressDialog.show();
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                File file = Directory.getExcelFile();
                try {
                    List<InventoryTaskSub> subDataList = mDbManager.findTaskSubList();
                    peopleRecyclerAdapter = new PeopleRecyclerAdapter();
                    peopleRecyclerAdapter.add(new People("库位", "条码","款式", "实际数", "多于", "差异"));
                    for (int i = 0; i < subDataList.size(); i++) {
                        peopleRecyclerAdapter.add(new People
                                ((subDataList.get(i).getLocation()), (subDataList.get(i).getBarode()), (subDataList.get(i).getCode()), (subDataList.get(i).getDiscNumber() + ""), (subDataList.get(i).getMoreThan() + ""), (subDataList.get(i).getLessThan() + "")));
                    }
                    ExcelUtils.write(file, peopleRecyclerAdapter.getPeoples());
                } catch (final IOException e) {
                    e.printStackTrace();

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(SameActivity.this, "Error : " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });


                    return null;
                } catch (final WriteException e) {
                    e.printStackTrace();
                   runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(SameActivity.this, "Error : " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                    return null;
                }
                return file.getAbsolutePath();
            }

            @Override
            protected void onPostExecute(String path) {
                progressDialog.dismiss();
                if (TextUtils.isEmpty(path))
                    Toast.makeText(SameActivity.this, "Gagal mengekspor", Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(SameActivity.this, "Berhasil mengekspor" + path, Toast.LENGTH_SHORT).show();
            }
        }.execute();
    }
}
